package com.polaris.live.ui.live.activity.end.call

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import com.bumptech.glide.Glide
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.R
import com.polaris.live.adapter.CallLabelAdapter
import com.polaris.live.adapter.CallSelectLabelAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.network.request
import com.polaris.live.common.util.DateUtils.Companion.minuteSChangeTime
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityCallEndBinding
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.CallStartResp
import com.polaris.live.resp.back_resp.CallVo
import com.polaris.live.resp.event.CallEndEvent
import com.polaris.live.resp.event.LiveRechargeEvent
import com.polaris.live.resp.go_resp.SaveCallLabelBean
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartCallProxy
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.CallEndViewModel
import com.polaris.live.widget.pag.AddFollowView.Companion.LIVE_ADD_FOLLOWE
import jp.wasabeef.glide.transformations.BlurTransformation
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.libpag.PAGView

/**
 * CallEndActivity  此页是支付方结算页面   因为与另一个结算页面的差距较大 而且逻辑也不太一样 所以分开写了
 *
 * @author Created by 半仙 on 2023/9/11/011 20:12
 */
class PayCallEndActivity : BaseVbActivity<CallEndViewModel, ActivityCallEndBinding>() {

    private var mCallInfo: CallVo? = null
    private var mCallBean: CallStartResp? = null
    private var mCallMessage: CallSignalingMessage? = null

    private val mAdapter: CallLabelAdapter by lazy {
        CallLabelAdapter()
    }

    private val labelAdapter: CallSelectLabelAdapter by lazy {
        CallSelectLabelAdapter()
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .titleBar(mBinding.icBack)
            .fullScreen(false)
            .transparentNavigationBar()
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)

        mCallInfo = intent.getParcelableExtra(LiveConst.Params.CALL_INFO)
        mCallBean = intent.getParcelableExtra(LiveConst.Params.CALL_BEAN)
        mCallMessage = intent.getParcelableExtra(LiveConst.Params.CALL_MESSAGE)

        initMy()
        initOther()
        initListener()
        initObsever()

        val flexBoxLayout = FlexboxLayoutManager(this)
        flexBoxLayout.flexDirection = FlexDirection.ROW
        flexBoxLayout.justifyContent = JustifyContent.FLEX_START
        flexBoxLayout.flexWrap = FlexWrap.WRAP
        mBinding.recycler.apply {
            layoutManager = flexBoxLayout
            adapter = mAdapter
        }
        mBinding.labelRecycler.apply {
            layoutManager =
                LinearLayoutManager(this@PayCallEndActivity, RecyclerView.HORIZONTAL, false)
            adapter = labelAdapter
            itemAnimator = null
        }

        val callInfo = mCallInfo
        if (callInfo != null) {
            mBinding.callEndOnLineTime.text =
                minuteSChangeTime(callInfo.onlineTime * 1000L).convertArabicDigitsToNormal()
            val money = callInfo.payCoin + callInfo.paySendCoin

            mBinding.country.setCountry(mCallMessage?.country)
            if (UserManager.getUser().profile?.secondCountryHidden == AppConst.YES.toLong()) {
                mBinding.myCountry.visibility = View.GONE
            } else {
                mBinding.myCountry.setCountry(UserManager.getUser().profile?.secondCountry)
            }


            mBinding.callEndPay.text = if (money == 0L) {
                mBinding.callEndPay.setTextColor(ColorUtils.getColor(R.color.a19f124))
                mBinding.ivDiamondUp.visibility = View.GONE
                "FREE"
            } else {
                "$money"
            }

            if (callInfo.follow) {
                mBinding.otherAddFollow.visibility = View.GONE
            }
        }

        mCallInfo?.id?.let { mViewModel.getCallLabel(it) }
        mViewModel.getUser()

        mBinding.otherAddFollow.apply {
            setPathType(LIVE_ADD_FOLLOWE)
            addListener(object : PAGViewListener {
                override fun onAnimationEnd(p0: PAGView?) {
                    super.onAnimationEnd(p0)
                    mBinding.otherAddFollow.visibility = View.INVISIBLE
                }
            })
            setRepeatCount(1)
        }
    }

    private fun initObsever() {
        mViewModel.mCallLabelLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (CollectionUtils.isEmpty(it)) {
                    mBinding.labelBottom.visibility = View.GONE
                } else {
                    mBinding.labelBottom.visibility = View.VISIBLE
                    mAdapter.setList(it)
                }
            })
        }
        mViewModel.mUserLiveData.observe(this) {
            mBinding.relCallEnd.visibility = View.VISIBLE
            if (mCallInfo?.follow == true) {
                mBinding.otherAddFollow.visibility = View.GONE
            }

            if (mCallInfo?.userFrom != LiveConst.SenderFrom.MATCH) {
                mBinding.matchNext.visibility = View.GONE
                mBinding.ivFree.visibility = View.GONE
            } else {
                if (it?.call?.callAsset == true) {
                    mBinding.ivFree.visibility = View.VISIBLE
                } else {
                    mBinding.ivFree.visibility = View.GONE
                }
            }
        }
        mViewModel.mLabelEndLiveData.observe(this) { resultState ->
            finish()
        }
    }

    private fun initMy() {
        val user = UserManager.getUser()
        mBinding.callEndMyHead.setImageUrlMiddle(
            user.avatar,
            user.userId
        )
        mBinding.callEndMyName.text = user.nickname

        user.account?.let {
            if (CommonUtils.isMan(user.sex)) {
                mBinding.myLevel.setRichsLevel(it.richs)
            } else {
                mBinding.myLevel.setCharmsLevel(it.charms)
            }
        }
        mBinding.vipViewMy.setVipLevel(user.profile?.vipLevel)
    }

    private fun initOther() {
        val otherUser = LiveUtils.getCallOtherUser(mCallBean, mCallMessage)

        mBinding.callEndOtherHead.setImageUrlMiddle(otherUser?.avatar)
        Glide.with(this).load(otherUser?.avatar?.let { ImageUtils.imgPath(it) })
            .transform(BlurTransformation(15, 3))
            .into(mBinding.callEndBigBackImg)

        mBinding.callEndOtherName.text = otherUser?.nickname
        val richs = otherUser?.richs ?: 0L
        val charm = otherUser?.charms ?: 0L

        if (otherUser?.sex?.let { CommonUtils.isMan(it) } == true) {
            mBinding.otherLevel.setRichsLevel(richs)
        } else {
            mBinding.otherLevel.setCharmsLevel(charm)
        }
        mBinding.vipViewOther.setVipLevel(otherUser?.vipLevel)
    }

    private fun initListener() {
        mBinding.icBack.setOnSingleClickListener {
            upLoadLabel()
        }

        mBinding.otherAddFollow.setOnSingleClickListener {
            mCallBean?.answer?.userId?.let { mViewModel.addFollower(it) }
        }

        mViewModel.mAddFollowerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(com.polaris.live.translation.R.string.follower_succeed)
                mBinding.otherAddFollow.play()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            if (labelAdapter.data.size < 2) {
                var isHave = false
                labelAdapter.data.forEach {
                    if (it.label == mAdapter.data[position].label) {
                        isHave = true
                    }
                }

                if (!isHave) {
                    labelAdapter.addData(mAdapter.data[position])
                }
            }
        }

        labelAdapter.setOnItemClickListener { _, _, position ->
            labelAdapter.removeAt(position)
        }

        mBinding.nextLabel.setOnSingleClickListener {
            mCallInfo?.id?.let { mViewModel.getCallLabel(it) }
        }
        mBinding.callBackStart.setOnSingleClickListener {
            if (labelAdapter.data.size > 0) {
                mCallInfo?.id?.let { it ->
                    val labels = mutableListOf<Int>()
                    labelAdapter.data.forEach {
                        labels.add(it.label)
                    }
                    mViewModel.request(
                        { liveService.saveCallLabel(SaveCallLabelBean(it, labels)) },
                        {
                            startCall()
                        })
                }
            } else {
                startCall()
            }
        }
        mBinding.matchNext.setOnSingleClickListener {
            if (labelAdapter.data.size > 0) {
                mCallInfo?.id?.let { it ->
                    val labels = mutableListOf<Int>()
                    labelAdapter.data.forEach {
                        labels.add(it.label)
                    }
                    mViewModel.request(
                        { liveService.saveCallLabel(SaveCallLabelBean(it, labels)) },
                        {
                            startMatch()
                        })
                }
            } else {
                startMatch()
            }
        }
    }

    private fun startMatch() {
        StartCallProxy.builder(this).startMatch(mViewModel) {
            finish()
        }
    }

    private fun startCall() {
        mCallInfo?.answerId?.let {
            val userBasic = LiveUtils.getCallOtherUser(mCallBean, mCallMessage)

            StartCallProxy.builder(this).startCall(
                mViewModel,
                UserConst.From.CALL_END,
                UserConst.LastFrom.CALL_END,
                LiveConst.SenderFrom.MANUAL,
                it,
                userBasic
            )
        }
    }

    private fun upLoadLabel() {
        if (labelAdapter.data.size > 0) {
            mCallInfo?.id?.let { it ->
                val labels = mutableListOf<Int>()
                labelAdapter.data.forEach {
                    labels.add(it.label)
                }
                mViewModel.saveCallLabel(it, labels)
            }
        } else {
            finish()
        }
    }

    override fun onBackPressed() {
        upLoadLabel()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: CallEndEvent) {
        finish()
    }

    //TODO 暂时先放置   就是如果通话过程中充值弹窗 弹出后不要关闭  后续想办法吧结束页融到通话页
    //之前融到一起过  但是点击回拨必出问题
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onCallRechargeEvent(event: LiveRechargeEvent) {
        EventBus.getDefault().removeStickyEvent(event)

        if (event.isShowRecharge == true) {
            GlobalPopupManager.showRechargePopup(this, mViewModel, isNeedBottom = true)
        } else if (event.isShowRecharge == false) {
            GlobalPopupManager.showTodayRecharge(mViewModel)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}